using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class Pathfinding : MonoBehaviour 
{
    public float StopDistance;
    public bool DrawWayInEditor = false;
    //[SerializeField]
    private List<Vector3> Path = new List<Vector3>();
    private bool stoppath = false;
    [Header("角色控制器")]
    public CharacterController characterController;
    public float speed;
    public bool isruning
    {
        get
        {
            return (Path.Count > 0) && (!stoppath);
        }
    }

    public void stop()
    {
        stoppath = true;
    }

    public void FindPath(Vector3 endPosition)
    {
        if (Vector3.Distance(transform.position,endPosition) > StopDistance)
        {
            Pathfinder.Instance.InsertInQueue(transform.position, endPosition, SetList);
            stoppath = false;
        }
        else
        {
            stoppath = true;
        }
    }
	

    //A test move function, can easily be replaced
    public void Move()
    {
        if (Path.Count > 0)
        {
            Vector3 pos = new Vector3(Path[0].x, transform.position.y, Path[0].z);
            transform.LookAt(pos);
            //Vector3 pos = (Path[0] - transform.position).normalized;
            pos = (pos - transform.position).normalized;
            characterController.SimpleMove(pos * speed);
            //transform.position = Vector3.MoveTowards(transform.position, Path[0], Time.deltaTime * 30F);
            if (Vector3.Distance(transform.position, Path[0]) < 0.25F)
            {
                Path.RemoveAt(0);
            }
        }
    }

    protected void SetList(List<Vector3> path)
    {
        if (path == null)
        {
            return;
        }
        Path.Clear();
        Path = path;
    }

    void Update()
    {
        if(DrawWayInEditor && Path.Count > 2)
        {
            for(int i = Path.Count-2; i>= 0; i--)
            {
                UnityEngine.Debug.DrawLine(Path[i+1], Path[i], Color.red);
            }
        }
        if (!stoppath) 
        {
            Move();

        }

    }
}
	
